using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Application.Service.Operation.Dto;
using Admin.NET.Core;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace Admin.NET.Application.Service.Operation;

/// <summary>
/// 操作日志
/// </summary>
[ApiDescriptionSettings(new string[] { "业务应用" }, Order = 100)]
public class OperationLogService : IDynamicApiController, ITransient, IPrivateDependency
{
	private readonly SqlSugarRepository<OperationLog> _rep;

	public OperationLogService(SqlSugarRepository<OperationLog> rep)
	{
		_rep = rep;
	}

	/// <summary>
	/// 分页查询
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpGet("/operationlog/page")]
	public async Task<dynamic> Page([FromQuery] OperationLogInput input)
	{
		ISugarQueryable<OperationLog> query = (from x in _rep.Context.Queryable<OperationLog>()
			where x.CreateTime >= input.StartTime && x.CreateTime <= input.EndTime
			select x).WhereIF(input.DeviceId.HasValue, (OperationLog u) => u.OperaId == input.DeviceId);
		query = query.OrderBuilder(input);
		SqlSugarPagedList<OperationLog> result = await query.ToPagedListAsync(input.Page, input.PageSize);
		List<OperationLog> meters = result.Items.Where((OperationLog u) => u.OperatName.Contains("电表")).ToList();
		if (meters.Count > 0)
		{
			List<long?> ids = meters.Select((OperationLog u) => u.OperaId).ToList();
			var meterInfo = await (from u in _rep.Context.Queryable<ElectricMeter>()
				where ids.Contains(u.Id)
				select new { u.Id, u.Sn, u.Name }).ToListAsync();
			meters.ForEach(delegate(OperationLog u)
			{
				var anon = meterInfo.Where(s => s.Id == u.OperaId).FirstOrDefault();
				if (anon != null)
				{
					u.Operat = anon.Sn + "-" + anon.Name;
				}
			});
		}
		return result;
	}
}
